#include "DXUT.h"
#include "SDKmisc.h"
#include "HDRImageMgr.h"

HDRImageMgr g_hdrImageMgr;

/**
*/
HDRImageMgr::HDRImageMgr() : m_pTexture( NULL ), m_pSRView( NULL )
{
}

/**
*/
HDRImageMgr::~HDRImageMgr()
{
}

/**
*/
HRESULT HDRImageMgr::LoadDefaultImage( ID3D11Device* pd3dDevice )
{
    Destroy();

    HRESULT hr = S_OK;

    // load cornell box if no image has been loaded previously.
    if( m_strFilePath.empty() )
    {
        WCHAR strFilePath[MAX_PATH];
        V_RETURN( DXUTFindDXSDKMediaFileCch( strFilePath, MAX_PATH, L"cornellbox.dds" ) );
        V_RETURN( LoadImage( pd3dDevice, strFilePath ) );
    }
    else 
    {
        // load previously loaded image
        V_RETURN( LoadImage( pd3dDevice, m_strFilePath ) );
    }
    
    return hr;
}

/**
*/
HRESULT HDRImageMgr::LoadImage( ID3D11Device* pd3dDevice, const std::wstring& strFilePath )
{
    Destroy();

    HRESULT hr = S_OK;

    D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
    D3D11_TEXTURE2D_DESC desc;
    ZeroMemory( &srvDesc, sizeof(srvDesc) );

    // Load the texture and initialize an ID3D11Texture2D object.
    V_RETURN( D3DX11CreateTextureFromFile( pd3dDevice, strFilePath.c_str(), NULL, NULL, reinterpret_cast< ID3D11Resource** >( &m_pTexture ), NULL ) );

    // Get a texture description to determine the texture
    // format of the loaded texture.
    m_pTexture->GetDesc( &desc );

    m_desc = desc;

    // Fill in the D3D11_SHADER_RESOURCE_VIEW_DESC structure.
    srvDesc.Format = desc.Format;
    srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
    srvDesc.Texture2D.MipLevels = 1; //desc.MipLevels;
    srvDesc.Texture2D.MostDetailedMip = 0; //desc.MipLevels-1;

    // Create the shader resource view.
    V_RETURN( pd3dDevice->CreateShaderResourceView( m_pTexture, &srvDesc, &m_pSRView ) );

    m_strFilePath = strFilePath;

    return hr;
}

/**
*/
void HDRImageMgr::Destroy()
{
    SAFE_RELEASE( m_pTexture );
    SAFE_RELEASE( m_pSRView );
}
